package com.chinasoft.mall.service;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import com.chinasoft.mall.framework.Config;
import com.chinasoft.mall.framework.ControllerCenter;
import com.chinasoft.mall.framework.Processor;
import com.chinasoft.mall.model.BaseBean;

public class PushMessageService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (tt != null) {
				tt.cancel(); // 将原任务从队列中移除
		}
		tt = new PushMessageTask(); // 新建一个任务
		timer.scheduleAtFixedRate(tt, 0, 30000);
	}

	private Timer timer = new Timer();
	private PushMessageTask tt ;
	 
	class PushMessageTask extends TimerTask {
		@Override
		public void run() {
			Log.e("running", "running");
			SharedPreferences mSharedPreferences = PushMessageService.this
					.getSharedPreferences("switch", Context.MODE_PRIVATE);
			boolean tag = mSharedPreferences.getBoolean("value", false);
			if (isTopActivity(PushMessageService.this)) {
				if (tag) {
					Log.i("OrderGoods", "请求");
					BaseBean getdatas = new BaseBean(Config.GET_GAME);
					getdatas.setUrl_type((byte) 1);
					ControllerCenter.getInstance().postMessage(getdatas);
					Log.e("OrderGoods", "开");
				} else {
					BaseBean getYylData = new BaseBean(Config.GET_MESSAGE);
					getYylData.setUrl_type((byte) 1);
					ControllerCenter.getInstance().postMessage(getYylData);
					Log.e("OrderGoods", "关");
				}
			}else{
				Log.e("========", "on background");
				if (tag) {
					BaseBean getdatas = new BaseBean(Config.GET_GAME);
					getdatas.setUrl_type((byte) 1);
					Processor.getInstance().handlePushMessage(getdatas,PushMessageService.this);
					Log.e("OrderGoods", "开");
				} else {
					BaseBean getYylData = new BaseBean(Config.GET_MESSAGE);
					getYylData.setUrl_type((byte) 1);
					Processor.getInstance().handlePushMessage(getYylData,PushMessageService.this);
					Log.e("OrderGoods", "关");
				}
			}
		}
	}

	

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e("destroy", "destroy");
	}

	protected static boolean isTopActivity(Context context) {
		String packageName = "com.chinasoft.mall";
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				return true;
			}
		}
		return false;
	}

}
